package com.daydayup.learn;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 对List中的元素去重
 */
public class ListRemoveDuplicates {
    public static void main(String[] args) {
        //m1();
        //m2();
        m3();
        //m4();
        //m5();
    }


    static void m1() {
        List<Integer> initList = Arrays.asList(70,70,-1,5,3,3,4,4,4,4,99);
        List<Integer> srcList = new ArrayList<>(initList);
        List<Integer> newList = new ArrayList<>();
        for (Integer val : srcList) {
            if (!newList.contains(val)) {
                newList.add(val);
            }
        }
        System.out.println(newList);
    }

    static void m2() {
        List<Integer> initList = Arrays.asList(70,70,-1,5,3,3,4,4,4,4,99);
        List<Integer> srcList = new ArrayList<>(initList);
        Set<Integer> treeSet = new LinkedHashSet<>(srcList);
        System.out.println(treeSet);
    }

    static void m3() {
        List<Integer> initList = Arrays.asList(70,70,-1,5,3,3,4,4,4,4,99);
        List<Integer> srcList = new ArrayList<>(initList);
        List<Integer> newList = srcList.stream().distinct().collect(Collectors.toList());
        System.out.println(newList);
    }
    /**
     * 循环坐标去除重复,类似双指针,按照值找到下标
     * 如果下标不同,表示有重复需要删除
     */
    static void m4() {
        List<Integer> initList = Arrays.asList(70,70,-1,5,3,3,4,4,4,4,99);
        List<Integer> srcList = new ArrayList<>(initList);
        List<Integer> newList = new ArrayList<>(initList);
        for (Integer e : srcList) {
            if (newList.indexOf(e) != newList.lastIndexOf(e)) {
                newList.remove(newList.lastIndexOf(e));
            }
        }
        newList.forEach( s -> System.out.print(s+" "));
    }

    static void m5() {
        List<Integer> initList = Arrays.asList(70,70,-1,5,3,3,4,4,4,4,99);
        List<Integer> newList = new ArrayList<>(initList);

        for (int i = 0; i < newList.size(); i++) {
            for (int j = newList.size()-1; j > i; j--) {
                if (newList.get(i).equals(newList.get(j))) {
                    newList.remove(j);
                }
            }
        }
        newList.forEach( s -> System.out.print(s+" "));
    }

}
